<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input
          v-model="queryParams.username"
          placeholder="请输入用户名"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="手机号" prop="mobile">
        <el-input
          v-model="queryParams.mobile"
          placeholder="请输入手机号"
          clearable
          @keyup.enter="handleQuery"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择用户状态"
          clearable
          class="!w-240px"
        >
          <el-option label="正常" :value="0" />
          <el-option label="停用" :value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="认证状态" prop="isAuth">
        <el-select
          v-model="queryParams.isAuth"
          placeholder="请选择认证状态"
          clearable
          class="!w-240px"
        >
          <el-option label="已认证" :value="1" />
          <el-option label="未认证" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          value-format="YYYY-MM-DD HH:mm:ss"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['weiyi:user:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['weiyi:user:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table 
      v-loading="loading" 
      :data="list" 
      :stripe="true" 
      :show-overflow-tooltip="true"
      style="width: 100%"
      border
    >
      <el-table-column label="用户ID" align="center" prop="id" width="80" />
      <el-table-column label="用户名" align="center" prop="username" min-width="120" />
      <el-table-column label="真实姓名/昵称" align="center" min-width="120">
        <template #default="{ row }">
          {{ row.nickname || row.realName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="头像" align="center" width="80">
        <template #default="{ row }">
          <el-avatar v-if="row.avatar" :src="row.avatar" :size="40" />
          <el-avatar v-else :size="40" icon="ep:user" />
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="mobile" min-width="120" />
      <el-table-column label="邮箱" align="center" prop="email" min-width="150" />
      <el-table-column label="类型" align="center" width="80">
        <template #default="{ row }">
          <el-tag v-if="row.userType === 1" type="success">直客</el-tag>
          <el-tag v-else-if="row.userType === 2" type="warning">渠道</el-tag>
          <el-tag v-else type="info">未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template #default="{ row }">
          <el-switch
            v-model="row.status"
            :active-value="0"
            :inactive-value="1"
            @change="handleStatusChange(row)"
            v-hasPermi="['weiyi:user:update']"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="170"
      />
      <el-table-column
        label="最后登录时间"
        align="center"
        prop="loginDate"
        :formatter="dateFormatter"
        width="170"
      />
      <el-table-column label="操作" align="center" width="220" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['weiyi:user:update']"
          >
            编辑
          </el-button>
          <el-button
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
            v-hasPermi="['weiyi:user:delete']"
          >
            删除
          </el-button>
          <el-button
            link
            type="warning"
            @click="openResetPwdDialog(scope.row)"
            v-hasPermi="['weiyi:user:reset-pwd']"
          >
            重置密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <UserForm ref="formRef" @success="getList" />
  
  <!-- 重置密码弹窗 -->
  <el-dialog
    v-model="resetPwdDialogVisible"
    title="重置密码"
    width="400px"
    destroy-on-close
  >
    <el-form :model="resetPwdForm" :rules="resetPwdRules" ref="resetPwdFormRef" label-width="80px">
      <el-form-item label="用户名">
        <span>{{ resetPwdForm.username }}</span>
      </el-form-item>
      <el-form-item label="新密码" prop="password">
        <el-input 
          v-model="resetPwdForm.password" 
          type="password" 
          placeholder="请输入新密码"
          show-password
        />
      </el-form-item>
      <el-form-item label="确认密码" prop="confirmPassword">
        <el-input 
          v-model="resetPwdForm.confirmPassword" 
          type="password" 
          placeholder="请再次输入新密码"
          show-password
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <el-button @click="resetPwdDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handleResetPwd" :loading="resetPwdLoading">确认</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref, unref } from 'vue'
import { ElMessageBox } from 'element-plus'
import { UserApi } from '@/api/weiyi/user'
import UserForm from './UserForm.vue'
import { dateFormatter } from '@/utils/formatTime'
import { useMessage } from '@/hooks/web/useMessage'
import { CommonStatusEnum } from '@/utils/constants'
import { useI18n } from '@/hooks/web/useI18n'

const message = useMessage() // 消息提示
const loading = ref(false) // 列表加载状态
const total = ref(0) // 列表总数
const list = ref([]) // 列表数据
const queryParams = ref({ // 查询参数
  pageNo: 1,
  pageSize: 10,
  username: undefined,
  mobile: undefined,
  status: undefined,
  isAuth: undefined,
  createTime: [],
  beginCreateTime:'',
  endCreateTime:''
})
const queryFormRef = ref() // 查询表单
const formRef = ref() // 表单
const exportLoading = ref(false) // 导出状态

// 重置密码相关
const resetPwdDialogVisible = ref(false)
const resetPwdLoading = ref(false)
const resetPwdFormRef = ref()
const resetPwdForm = ref({
  id: 0,
  username: '',
  password: '',
  confirmPassword: ''
})

// 重置密码校验规则
const resetPwdRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== resetPwdForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

/** 查询列表 */
const getList = async () => {
  try {
    loading.value = true
    // 处理时间范围
    const params: any = { ...unref(queryParams) }
    
    if (params.createTime && params.createTime.length > 0) {
      params.beginCreateTime = params.createTime[0]
      params.endCreateTime = params.createTime[1]
    }
    delete params.createTime
    
    const response = await UserApi.getUserPage(params)
    
    // 检查响应结构，直接使用顶层的list和total属性
    if (response && response.list) {
      list.value = response.list || []
      total.value = response.total || 0
    } else {
      list.value = []
      total.value = 0
    }
  } catch (error) {
    list.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

/** 搜索 */
const handleQuery = () => {
  queryParams.value.pageNo = 1
  getList()
}

/** 重置搜索条件 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 打开表单弹窗 */
const openForm = (type: string, id?: number) => {
  formRef.value?.open(type, id)
}

/** 导出 */
const handleExport = async () => {
  try {
    exportLoading.value = true
    await UserApi.exportUser(queryParams.value)
  } catch (error) {
    console.error('导出失败:', error)
  } finally {
    exportLoading.value = false
  }
}

/** 修改用户状态 */
const handleStatusChange = async (row) => {
  try {
    // 修改状态的二次确认
    const text = row.status === CommonStatusEnum.ENABLE ? '启用' : '停用'
    await message.confirm('确认要"' + text + '""' + row.username + '"用户吗?')
    // 发起修改状态
    await UserApi.updateUserStatus(row.id, row.status)
    message.success(`${text}成功`)
    // 刷新列表
    await getList()
  } catch(error) {
    // 取消后，进行恢复按钮
    row.status =
      row.status === CommonStatusEnum.ENABLE ? CommonStatusEnum.DISABLE : CommonStatusEnum.ENABLE
      if (error !== 'cancel') {
      console.error('修改状态失败:', error)
      message.error('修改状态失败')
    }
  }
}

/** 删除 */
const handleDelete = async (id: number) => {
  try {
    await ElMessageBox.confirm('是否确认删除该用户？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })
    
    await UserApi.deleteUser(id)
    message.success('删除成功')
    if (list.value.length === 1 && queryParams.value.pageNo > 1) {
      queryParams.value.pageNo--
    }
    await getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

/** 打开重置密码弹窗 */
const openResetPwdDialog = (row) => {
  resetPwdDialogVisible.value = true
  resetPwdForm.value = {
    id: row.id,
    username: row.username,
    password: '',
    confirmPassword: ''
  }
}

/** 重置密码 */
const handleResetPwd = async () => {
  if (!resetPwdFormRef.value) return
  
  try {
    await resetPwdFormRef.value.validate()
    
    resetPwdLoading.value = true
    await UserApi.resetUserPassword(resetPwdForm.value.id, resetPwdForm.value.password)
    message.success('重置密码成功')
    resetPwdDialogVisible.value = false
  } catch (error) {
    console.error('重置密码失败:', error)
    if (error !== 'cancel') {
      message.error('重置密码失败')
    }
  } finally {
    resetPwdLoading.value = false
  }
}

/** 初始化 **/
onMounted(() => {
  getList()
})
</script> 